package admin.controllers;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.google.appengine.labs.repackaged.org.json.JSONObject;
import com.google.gson.Gson;

import entities.Category;

import admin.models.CategoryModel;

@SuppressWarnings("serial")
public class CategorySendServlet extends HttpServlet 	{
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		String siteUrl = "";
		String sl = "en";
		String tl = "en";
		
		request.setAttribute("siteUrl", siteUrl);
		request.setAttribute("sl", sl);
		request.setAttribute("tl", tl);
		try {
			request.getRequestDispatcher("/admin/pages/category_send.jsp").forward(request, response);
		} catch (ServletException e) {
			//
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String siteUrl = (String) request.getParameter("siteUrl");
		String sl = (String) request.getParameter("sl");
		String tl = (String) request.getParameter("tl");
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		List<Category> categories = categoryModel.getAll();
		
		Map<String, String> params = new TreeMap<String, String>();
		
		for (Category category : categories) {
			params.put(category.getId(), category.getName());
		}
		
		if (siteUrl != null && !siteUrl.isEmpty()) {
			Connection conn = Jsoup.connect(siteUrl);
			
			String data = new Gson().toJson(params);
			
			Document doc = conn
				.header("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
				.header("accept-Language", "en-us,en;q=0.5")
				.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1")
				.data("data", data)
				.data("sl", sl)
				.data("tl", tl)
				.followRedirects(false)
				.post();
			
			request.setAttribute("success", "submit success category to " +  siteUrl);
		}
		
		request.setAttribute("siteUrl", siteUrl);
		request.setAttribute("sl", sl);
		request.setAttribute("tl", tl);
		try {
			request.getRequestDispatcher("/admin/pages/category_send.jsp").forward(request, response);
		} catch (ServletException e) {
			//
		}
	}
}
